package CLIENTS;

import java.io.IOException;

import ocsf.client.AbstractClient;

/**
 * This class sent message to server
 * @author michael
 *
 */
public class Client extends AbstractClient
{
	private Object messagefromserver = null;
	private boolean readytoread = false;
	private boolean readytosend = true;
	
	/**
	 * @param host
	 * @param port
	 */
	public Client(String host, int port) throws IOException
	{
		super(host, port);
		openConnection();
	}

	
	/**
	 * @return the messagefromserver
	 */
	public synchronized Object getMessagefromserver()
	{
		readytosend = true;
		return messagefromserver;		
	}
		
	/**
	 * @return the readytoread
	 */
	public synchronized boolean isReadytoread() 
	{
		return readytoread;
	}

	/**
	 * 
	 * 
	 */
	protected synchronized void handleMessageFromServer(Object msg)
	{
		try
		{
			if (msg.getClass() == String.class)
			{
				if (((String)(msg)).equals("CHECK"))
				{
					System.out.println("CHECK");
						return;
				}
			}
			this.messagefromserver = msg;
			readytoread = true;
		}catch(Exception e) 
		{
			messagefromserver = null;
		};		
	}
	
	  /**
	   * This method handles all data coming from the UI            
	   *
	   * @param message The message from the UI.    
	   */
	  public synchronized void handleMessageFromClientUI(String[] message)
	  {
		  if (!readytosend)
			  return;
		  try
		  {
			  	sendToServer(message);	
			  	readytoread = false;
			  	readytosend = false;
		  }
		  catch(IOException e)
		  {
			  System.out.println("Could not send message to server.  Terminating client.");
			  quit();
		  }
	  }  
	  	  
	  /**
	   * This method terminates the client.
	   */
	  public void quit()
	  {
		try
	    {
			 closeConnection();		     
	    }
	    catch(IOException e) {}	    
	    System.exit(0);
	  }
	  
	  public void finalize()
	  {
		  System.exit(0); 		
	  }
	  
	  	
}


